package online.afeibaili.storebackendframework.server;

import online.afeibaili.storebackendframework.mapper.ProductMapper;
import online.afeibaili.storebackendframework.model.Product;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class ProductServer {
    private static final Logger log = LoggerFactory.getLogger(ProductServer.class);
    private final ProductMapper productMapper;
    public static String path = System.getProperty("user.dir");

    public ProductServer(ProductMapper productMapper) {
        this.productMapper = productMapper;
    }

    public int insert(Product product, MultipartFile[] images, MultipartFile[] videos) {
        try {
            File imageDir = new File(path + File.separator + "image");
            File videoDir = new File(path + File.separator + "video");
            if (!videoDir.exists()) {
                boolean mdDirCreated = videoDir.mkdirs();
                if (!mdDirCreated) {
                    log.error("无法创建视频目录: {}", videoDir.getAbsolutePath());
                    throw new RuntimeException("无法创建视频目录: " + videoDir.getAbsolutePath());
                }
            }
            if (!imageDir.exists()) {
                boolean imageDirCreated = imageDir.mkdirs();
                if (!imageDirCreated) {
                    log.error("无法创建图片目录: {}", imageDir.getAbsolutePath());
                    throw new RuntimeException("无法创建图片目录: " + imageDir.getAbsolutePath());
                }
            }

            // 保存文件
            List<String> imagePaths = new ArrayList<>();
            List<String> videoPaths = new ArrayList<>();

            if (images != null) {
                for (MultipartFile image : images) {
                    if (image != null && !image.isEmpty()) {
                        try {
                            saveImage(image, imagePaths, imageDir);
                        } catch (IOException e) {
                            log.error("图片文件保存失败", e);
                            throw new RuntimeException("图片文件保存失败", e);
                        }
                    }
                }
            }

            if (videos != null) {
                for (MultipartFile video : videos) {
                    if (video != null && !video.isEmpty()) {
                        try {
                            saveVideo(video, videoPaths, videoDir);
                        } catch (IOException e) {
                            log.error("视频文件保存失败", e);
                            throw new RuntimeException("视频文件保存失败", e);
                        }
                    }
                }
            }

            // 更新产品对象中的文件路径，使用逗号分隔多个文件路径
            product.setImages(String.join(",", imagePaths));
            product.setVideo(String.join(",", videoPaths));

            return productMapper.insert(product);
        } catch (Exception e) {
            log.error("产品插入过程中发生错误", e);
            return 0;
        }
    }

    //删除
    public int delete(long createTime) {
        Product product = productMapper.selectByCreateTime(createTime);
        //判空
        if (product.getImages() != null) {
            String[] image = product.getImages().split(",");
            for (String s : image) {
                File file = new File(path + File.separator + s);
                if (file.exists()) {
                    boolean deleted = file.delete();
                    if (!deleted) {
                        log.error("无法删除图片该: {}", s);
                    }
                }
            }
        }
        if (product.getVideo() != null) {
            String[] video = product.getVideo().split(",");
            for (String s : video) {
                File file = new File(path + File.separator + s);
                if (file.exists()) {
                    boolean deleted = file.delete();
                    if (!deleted) {
                        log.error("无法删除视频: {}", s);
                    }
                }
            }
        }

        log.info("删除产品: {}", product.getName());
        return productMapper.delete(createTime);
    }

    public int deleteImage(String imageName, long createTime) {
        String image = productMapper.selectImageByCreateTime(createTime);
        if (image == null) {
            return 0;
        }
        String[] images = image.split(",");
        //productMapper.updateImage(imageName, createTime); 将图片名从数据库中删除仅选中的图片其他的不变
        for (int i = 0; i < images.length; i++) {
            if (images[i].equals(imageName)) {
                try {
                    File file = new File(path + File.separator + images[i]);
                    images[i] = null;
                    if (file.exists()) {
                        boolean deleted = file.delete();
                        if (!deleted) {
                            log.error("无法删除图片: {}", images[i]);
                        }
                    }
                } catch (Exception e) {
                    images[i] = null;
                    log.error("图片文件删除失败", e);
                }
            }
        }
        List<String> filteredImages = new ArrayList<>();
        for (String img : images) {
            if (img != null && !img.isEmpty()) {
                filteredImages.add(img);
            }
        }
        //删除数据库中所被选中的图片其他不变
        productMapper.updateImage(String.join(",", filteredImages), createTime);
        return 1;
    }

    public int deleteVideo(String videoName, long createTime) {
        String video = productMapper.selectVideoByCreateTime(createTime);
        if (video == null) {
            return 0;
        }
        String[] videos = video.split(",");
        //productMapper.updateImage(imageName, createTime); 将图片名从数据库中删除仅选中的图片其他的不变
        for (int i = 0; i < videos.length; i++) {
            if (videos[i].equals(videoName)) {
                try {
                    File file = new File(path + File.separator + videos[i]);
                    videos[i] = null;
                    if (file.exists()) {
                        boolean deleted = file.delete();
                        if (!deleted) {
                            log.error("无法删除该视频: {}", videos[i]);
                        }
                    }
                } catch (Exception e) {
                    videos[i] = null;
                    log.error("图片文件删除失败", e);
                }
            }
        }
        List<String> filteredVideo = new ArrayList<>();
        for (String vid : videos) {
            if (vid != null && !vid.isEmpty()) {
                filteredVideo.add(vid);
            }
        }
        //删除数据库中所被选中的视频其他不变
        productMapper.updateVideo(String.join(",", filteredVideo), createTime);
        return 1;
    }

    public int addImage(MultipartFile image, long createTime) {
        List<String> imagePaths = new ArrayList<>();
        String imageList = productMapper.selectImageByCreateTime(createTime);
        String productImage = (imageList == null|| imageList.isEmpty()) ? "" : imageList + ",";
        try {
            File imageDir = new File(path + File.separator + "image");
            saveImage(image, imagePaths, imageDir);
        } catch (IOException e) {
            log.error("图片文件保存失败", e);
            throw new RuntimeException("图片文件保存失败", e);
        }
        productMapper.updateImage(productImage + String.join(",", imagePaths), createTime);
        return 1;
    }

    public int addVideo(MultipartFile video, long createTime) {
        List<String> videoPaths = new ArrayList<>();
        String videoList = productMapper.selectVideoByCreateTime(createTime);
        String productVideo = (videoList == null|| videoList.isEmpty())? "" : videoList + ",";
        try {
            File videoDir = new File(path + File.separator + "video");
            saveVideo(video, videoPaths, videoDir);
        } catch (IOException e) {
            log.error("视频文件保存失败", e);
            throw new RuntimeException("视频文件保存失败", e);
        }
        productMapper.updateVideo(productVideo + String.join(",", videoPaths), createTime);
        return 1;
    }

    private void saveImage(MultipartFile image, List<String> imagePaths, File imageDir) throws IOException {
        String imageFileName = UUID.randomUUID() + "_" + image.getOriginalFilename();
        File imageTarget = new File(imageDir, imageFileName);
        Files.copy(image.getInputStream(), imageTarget.toPath(), StandardCopyOption.REPLACE_EXISTING);
        imagePaths.add("/image/" + imageFileName);  // 只保存文件名和相对路径
        log.info("图片文件保存成功: {}", "/image/" + imageFileName);
    }

    private void saveVideo(MultipartFile video, List<String> videoPaths, File videoDir) throws IOException {
        String videoFileName = UUID.randomUUID() + "_" + video.getOriginalFilename();
        File videoTarget = new File(videoDir, videoFileName);
        Files.copy(video.getInputStream(), videoTarget.toPath(), StandardCopyOption.REPLACE_EXISTING);
        videoPaths.add("/video/" + videoFileName);  // 只保存文件名和相对路径
        log.info("视频文件保存成功: {}", "/video/" + videoFileName);
    }

    public int count() {
        return productMapper.count();
    }

    public Product selectByCreateTime(long createTime) {
        return productMapper.selectByCreateTime(createTime);
    }

    public int updateSaleAdmin(long createTime, int sales) {
        return productMapper.updateSalesAdmin(createTime, sales);
    }

    public List<Map<String, Object>> selectPage(int start, int pageSize) {
        return productMapper.selectPage(start, pageSize);
    }

    //增加sales
    public int updateSales(long createTime) {
        return productMapper.updateSales(createTime);
    }

    //查询price
    public Map<String, Object> selectPrice(long createTime) {
        return productMapper.selectPrice(createTime);
    }

    // 批量查询价格和名称
    public List<Product> selectPricesByCreateTimes(List<Long> createTimes) {
        return productMapper.selectPricesByCreateTimes(createTimes);
    }
}